package com.zhj.psi.core.config;

import com.zhj.psi.web.dto.SecurityUser;
import com.zhj.psi.web.entity.Role;
import com.zhj.psi.web.entity.User;
import com.zhj.psi.web.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhuhuijun on 2017/8/31 16:20
 */
@Service
public class MyUserDetailService implements UserDetailsService {
    private Logger logger = LoggerFactory.getLogger(MyUserDetailService.class);
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userService.findByUsername(userName);
        if (user == null) {
            throw new BadCredentialsException("用户名不存在");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<Role> roleList = userService.listRoleByUserId(user.getId());
        for (Role role : roleList) {
            authorities.add(new SimpleGrantedAuthority(role.getCode()));
            logger.info(role.getName() + ":" + role.getCode());
        }
        SecurityUser securityUser = new SecurityUser(user.getUsername(), user.getPassword(),
                "PSI", authorities, true, true,
                true, true);
        return  securityUser;
    }
}
